package com.scholarship.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 日期工具类
 * @Author Z.J.H
 * @create 2021/8/25 21:43
 */
public class MyDateUtil {

    public static SimpleDateFormat UTC = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH);

    public static SimpleDateFormat YMD = new SimpleDateFormat("yyyy-MM-dd");

    public static SimpleDateFormat YMDHMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 判断日期格式
     * @param dateTime
     * @param sdf
     * @return
     */
    public static boolean isFormat(String dateTime,SimpleDateFormat sdf) {
        try {
            sdf.parse(dateTime);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    /**
     *
     * @param dateTime
     * @return
     * @throws ParseException
     */
    public static String UTCToYMD(String dateTime) throws ParseException {
        if(isFormat(dateTime,UTC)) {
            Date date = UTC.parse(dateTime);
            //转为北京时间（UTC + 8h），再返回年月日
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR) + 8);

            return YMD.format(calendar.getTime());
        }
        return dateTime;
    }

    /**
     *
     * @param dateTime
     * @return
     * @throws ParseException
     */
    public static String UTCToYMDHMS(String dateTime) throws ParseException {
        if(isFormat(dateTime,UTC)) {
            Date date = UTC.parse(dateTime);
            //转为北京时间（UTC + 8h），再返回年月日
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR) + 8);

            return YMDHMS.format(calendar.getTime());
        }
        return dateTime;
    }

    public static Date UTCToYMD(Date dateTime){
        //转为北京时间（UTC + 8h），再返回年月日
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateTime);
        calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR) + 8);
        return calendar.getTime();
    }
}
